<?php 
namespace app\backman\controller; 
use app\backman\model\Meal; 
use \app\common\controller\AuthBack; 
use \app\common\model\Category; 
use \app\common\model\OrderTestType; 
use app\common\model\Comment; 
use \app\common\model\Order as OrderItem; 
use \app\common\model\OrderS; 
use \app\common\model\Customer; 
use \app\common\model\Goods; 
use \app\common\model\Staff; 
use \app\common\model\Detection; 
use \app\common\model\DetectionSon; 
use \app\common\model\DetectionSpec; 
use \app\common\model\OrderSpec; 
use \app\backman\model\Delivery; 
use \app\backman\model\AgentLevel; 
use app\common\model\User; 
use think\Db;
use think\facade\App;
require_once App::getRootPath().'/extend/PHPExcel/PHPExcel.php';

class Order extends AuthBack{





    public function initialize(){

        parent::initialize();

    }



    public function index(){

        $like       = isset($_GET['like']) ? $_GET['like'] : '';
        $customer   = isset($_GET['customer']) ? $_GET['customer'] : '';
        $goods      = isset($_GET['goods']) ? $_GET['goods'] : '';
        $detection  = isset($_GET['detection']) ? $_GET['detection'] : '';
        $status     = isset($_GET['status']) ? $_GET['status'] : '';
        $start_time = isset($_GET['start_time']) ? $_GET['start_time'] : '';
        $end_time   = isset($_GET['end_time']) ? $_GET['end_time'] : '';

		$where = [];
        if(!empty(input('like'))){
            // 防伪号、流水号
            $where[] = ['o.order_sn|o.code','like',"%".input('like')."%"];
        }

        if( !empty(input('customer_id')) ){
            $where[] = ['o.customer_id','eq',input('customer_id')];
        }

        if( !empty(input('goods_id')) ){
            $where[] = ['o.goods_id','eq',input('goods_id')];
        }

        if( !empty(input('staff_id')) ){
            $where[] = ['o.staff_id','eq',input('staff_id')];
        }

        

        if( !empty(input('start_time')) && !empty(input('end_time')) ){
            $where[] = ['o.create_time','between',input('start_time').','.input('end_time')];
        }else{
            if( !empty(input('start_time')) ){
                $where[] = ['o.create_time','>=',input('start_time')];
            }
            if( !empty(input('end_time')) ){
                $where[] = ['o.create_time','<=',input('end_time')];
            }
        }

        $totalNum   = OrderItem::alias('o')
                    ->where($where)
                    ->count();

        $customer   = Customer::where('status',1)->field('id,customer_name')->select();

        $goods   = Goods::where('status',1)->field('id,title')->select();

        $staff   = Staff::where('status',1)->field('id,name')->select();

        if(request()->isAjax()){

            $page = isset($_GET['page']) ? $_GET['page'] : '1';
            $limit = isset($_GET['limit']) ? $_GET['limit'] : '20';
            $startNum = ($page - 1) * $limit;
            $totalPage = ceil($totalNum/$limit);

            $list = OrderItem::alias('o')
	                        ->join('goods g','o.goods_id = g.id')
                            ->where($where)
                            ->field('o.id,o.order_sn,o.customer_id,o.goods_id,o.staff_id,o.code,o.status,o.create_time,o.update_time,g.good_sn')
                            ->limit($startNum.','.$limit)
                            ->order('o.create_time desc')
                            ->select();


            if(empty($list)){
                return json(['code'=>0,'data'=>[],'total'=>$totalPage,'count'=>$totalNum]);
            }elseif($page > $totalPage){
                return json(['code'=>0,'data'=>[],'total'=>$totalPage+1,'count'=>$totalNum]);
            }else{
                $nList = array();
                if(!empty($list)){
                    foreach($list as $k=>$vo){
                        $nList[$k] = $vo;
                        $nList[$k]['customer_name'] = $vo['customer_id']['text'];
                        $nList[$k]['goods_title'] = $vo['goods_id']['text'];
                        $nList[$k]['staff_name'] = $vo['staff_id']['text'];
	                    $nList[$k]['code'] = str_pad($vo['code'],8,"0",STR_PAD_LEFT);
                    }
                }

                $return = [
                    'code'=>0,
                    'msg'=>'',
                    'count'=>$totalNum,
                    'data'=>$nList
                ];
                return json($return);
            }

        }else{
            $this->assign('totalNum',$totalNum);
            $this->assign('customer',$customer);
            $this->assign('staff',$staff);
            $this->assign('goods',$goods);
            return view();

        }

    }






    /**

     * 获取检测流程下的环节

     */

    public function getdetectionSon(){

        if( request()->isAjax() ){

            $data = $this->request->param();

            $list = DetectionSon::where(['parent_id'=>$data['id'],'status'=>1])->order('sort asc')->field('id,d_son_sn,name')->select();

            

            

            $return = [

                'code'=>0,

                'msg'=>'',

                'data'=>$list

            ];

            return json($return);

        }

    }



   /**

    * 检测单添加修改

    * 

    */

    public function option($id = 0){

        if(!request()->isPost()){

            

            $customer   = Customer::where('status',1)->field('id,customer_name')->select();

            $goods      = Goods::where('status',1)->field('id,title')->select();

            $detection  = Detection::where('status',1)->field('id,name')->select();

            $test_type  = OrderTestType::field('id,name')->select();

            $info = OrderItem::get($id);



            $this->assign('info',$info);

            $this->assign('customer',$customer);

            $this->assign('detection',$detection);

            $this->assign('goods',$goods);

            $this->assign('test_type',$test_type);

            // dump($info);exit();

            return view();

        }else{

            $obj = new OrderItem();

            // if( empty($this->data['cid']) ) return $this->error('客户不能为空');

            // if( empty($this->data['gid']) ) return $this->error('产品不能为空！');

            // if( empty($this->data['did']) ) return $this->error('检测流程不能为空！');

            // if( empty($this->data['gsid']) ) return $this->error('检测流程环节不能为空！');



            if( !empty($this->data['did']) ){

                if( empty($this->data['gsid']) ) return $this->error('检测流程环节不能为空！');

            }



            if($this->data['id']){

                // 编辑

                AdminLog($this->admin['id'],'修改检测单【'.$this->data['order_sn'].'】信息');

                $state = $obj->saveData($this->data,'edit');

            }else{

                // 新增

                AdminLog($this->admin['id'],'新增检测单【'.$this->data['order_sn'].'】');

                $state = $obj->saveData($this->data,'add',$this->admin);

            }

            if($state){

                return $this->success('操作成功',url('index'));

            }else{

                return $this->error($obj->getError());

            }

        }

    }



    public function update_status(){

        $data = $this->request->param();

        $update['status'] = $data['status'];

        $update['engding'] = $data['engding'];

        $update['updated_time'] = date('Y-m-d H:i:s');

        AdminLog($this->admin['id'],'修改检测单【'.$data['id'].'】状态');

        $res = Db::name('order')->where('id',$data['id'])->update($update);

        if(!$res){

            return json(['code'=>0,'msg'=>'请求失败']);

        }

        return json(['code'=>1,'msg'=>'请求成功']);

    }



    public function update_d_status(){

        $data = $this->request->param();

        $update['status'] = $data['status'];

        $update['updated_time'] = date('Y-m-d H:i:s');

        AdminLog($this->admin['id'],'修改检测单环节【'.$data['oid'].'-'.$data['dsid'].'】状态');

        $res = Db::name('order_d_s')->where(['oid'=>$data['oid'],'dsid'=>$data['dsid']])->update($update);

        if(!$res){

            return json(['code'=>0,'msg'=>'请求失败']);

        }

        return json(['code'=>1,'msg'=>'请求成功']);

    }

    public function update_s_status(){

        $data = $this->request->param();

        $update['status'] = $data['status'];

        $update['updated_time'] = date('Y-m-d H:i:s',time());

        AdminLog($this->admin['id'],'修改检测单表单【'.$data['id'].'】状态');

        $res = Db::name('order_s')->where(['id'=>$data['id']])->update($update);

        if(!$res){

            return json(['code'=>0,'msg'=>'请求失败']);

        }

        return json(['code'=>1,'msg'=>'请求成功']);

    }







    /**

     * 批量删除

     */

    public function delArr(){

        if( empty( $this->data['id'] ) ) return_ajax(40001,'error','参数错误');

        $idS = implode(',',$this->data['id']);

        AdminLog($this->admin['id'],'批量删除检测单信息【订单id'.$idS.'】');





        $state = DB::name('order')->where('id','in',$this->data['id'])->delete();

        

        if( $state ){

            return json(['code'=>1,'msg'=>'批量删除检测单成功']);

        }else{

            return json(['code'=>0,'msg'=>'批量删除检测单失败']);

        }





    }


    /**

     * 数据导出 Excel

     */

    public function load_excel(){

	    $where = [];
	    if(!empty(input('like'))){
		    // 防伪号、流水号
		    $where[] = ['o.order_sn|o.code','like',"%".input('like')."%"];
	    }

	    if( !empty(input('customer_id')) ){
		    $where[] = ['o.customer_id','eq',input('customer_id')];
	    }

	    if( !empty(input('goods_id')) ){
		    $where[] = ['o.goods_id','eq',input('goods_id')];
	    }

	    if( !empty(input('staff_id')) ){
		    $where[] = ['o.staff_id','eq',input('staff_id')];
	    }

	    if( !empty(input('start_time')) && !empty(input('end_time')) ){
		    $where[] = ['o.create_time','between',input('start_time').','.input('end_time')];
	    }else{
		    if( !empty(input('start_time')) ){
			    $where[] = ['o.create_time','>=',input('start_time')];
		    }
		    if( !empty(input('end_time')) ){
			    $where[] = ['o.create_time','<=',input('end_time')];
		    }
	    }


	    $list = OrderItem::alias('o')
		    ->join('goods g','o.goods_id = g.id')
		    ->where($where)
		    ->field('o.id,o.order_sn,o.customer_id,o.goods_id,o.staff_id,o.code,o.status,o.create_time,o.update_time,g.good_sn')
		    ->order('o.create_time desc')
		    ->select();

		    $nList = array();
		    if(!empty($list)){
			    foreach($list as $k=>$vo){
				    $nList[$k] = $vo;
				    $nList[$k]['customer_name'] = $vo['customer_id']['text'];
				    $nList[$k]['goods_title'] = $vo['goods_id']['text'];
				    $nList[$k]['staff_name'] = $vo['staff_id']['text'];
				    $nList[$k]['code'] = str_pad($vo['code'],8,"0",STR_PAD_LEFT);
			    }
		    }
            $excelName = ''.date('YmdHis');
            $this->exportExcel($nList,$excelName);


            exit();


    }



    public function exportExcel($data, $name){
        $objPHPExcel = new \PHPExcel();  //实例化  相当于在桌面新建一个excel
            // 表头
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', '核销人姓名')
                ->setCellValue('B1', '二维码')
                ->setCellValue('C1', '流水号')
                ->setCellValue('D1', '产品名称')
                ->setCellValue('E1', '产品编号')
                ->setCellValue('F1', '业务员名称')
                ->setCellValue('G1', '核销时间');
            //设置内容水平居中
            $objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            // 设置个表格宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(24);
            //设置单元格自动宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension("A")->setAutoSize(true);
            // 内容
            for ($i = 0, $len = count($data); $i < $len; $i++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue('A' . ($i + 2), $data[$i]['customer_name']);     //序号
	            $objPHPExcel->getActiveSheet(0)->setCellValue('B' . ($i + 2), $data[$i]['order_sn']);   // 二维码
	            $objPHPExcel->getActiveSheet(0)->setCellValue('C' . ($i + 2), $data[$i]['code']);   // 流水号
                $objPHPExcel->getActiveSheet(0)->setCellValue('D' . ($i + 2), $data[$i]['goods_title']);  // 产品名称
                $objPHPExcel->getActiveSheet(0)->setCellValue('E' . ($i + 2), $data[$i]['good_sn']);      // 产品编号
                $objPHPExcel->getActiveSheet(0)->setCellValue('F' . ($i + 2), $data[$i]['staff_name']);       // 业务员名称
                $objPHPExcel->getActiveSheet(0)->setCellValue('G' . ($i + 2), $data[$i]['create_time']);    // 核销时间
                //设置内容水平居中
                $objPHPExcel->setActiveSheetIndex(0)->getStyle($i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                
                $objPHPExcel->getActiveSheet()->getStyle('J' . ($i + 2))->getAlignment()->setWrapText(true);
            }
            $objPHPExcel->getActiveSheet()->setTitle('User');
            $objPHPExcel->setActiveSheetIndex(0);
            ob_end_clean();//清楚缓存区，解决乱码问题
            header("Pragma:public");
            header("Content-Type:application/x-msexecl;name=\"{$name}.xlsx\"");
            header("Content-Disposition:inline;filename=\"{$name}.xlsx\"");
            $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
            $objWriter->save('php://output');
            exit;
    }




}